package co.fitstart.admin.web.controller.user;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.utils.DateUtils;

import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.entity.usersource.UserSourceTranser;
import co.fitstart.admin.service.PrincipalService;
import co.fitstart.admin.service.SiteService;
import co.fitstart.admin.service.UserSourceService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.admin.web.view.ExcelTemplateView;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.site.Site;
import co.fitstart.entity.user.UserSource;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("/user-source-stat")
@MenuSetting("menu-source")
public class SourceStatController {

//	private static final Logger logger = LoggerFactory.getLogger(SourceStatController.class);

	@Autowired
	private SiteService siteService;
	
	@Autowired
	private UserSourceService userSourceService;
	
	@Autowired
	private PrincipalService principalService;

	/**
	 * 
	 * @param request
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.GET)
	@MenuSetting("submenu-source-stat-management")
	public ModelAndView list(@Secure Login login, 
			@RequestParam(value = "site", required = false) Long siteId,
			@RequestParam(value = "selectDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date selectDate,
			HttpServletRequest request) {

		ModelAndView modelAndView = new ModelAndView("source/user-source-stat-index");
		
		if(selectDate == null) {
			selectDate = new Date();
		}
		
		Date monthFirst = DateUtils.getFirstMonthDay(selectDate);
		Date monthLast = DateUtils.getLastMonthDay(selectDate);
		
		List<Site> sites = new ArrayList<Site>();
		
		if(siteId != null) {
			Site site = siteService.load(siteId);
			sites.add(site);
		} else if(login.isAdmin() || login.isRoot()) {
			sites = siteService.list();
		} else if (login.isAreaManager() || login.isAreaServer()) {
			Principal principal = principalService.load(Principal.class, login.getId());
            sites = siteService.listSite(principal);
		} else {
			Site site = login.getSite();
			sites.add(site);
		}
		
		List<UserSource> userSources = new ArrayList<UserSource>();
		userSources = userSourceService.listSource(monthFirst, monthLast, sites);
		Map<String, List<UserSourceTranser>> stat = new HashMap<String, List<UserSourceTranser>>(sites.size());
		
		for(Site site : sites) {
			List<UserSourceTranser> transers = new LinkedList<UserSourceTranser>();
			transers.add(new UserSourceTranser(site, "大众点评"));
			transers.add(new UserSourceTranser(site, "访客"));
			transers.add(new UserSourceTranser(site, "转介绍"));
			transers.add(new UserSourceTranser(site, "店长资源"));
			transers.add(new UserSourceTranser(site, "线下运营"));
			transers.add(new UserSourceTranser(site, "在营续课"));
			transers.add(new UserSourceTranser(site, "结营续课"));
			
			stat.put(site.getName(), transers);
		}
		modelAndView.addObject("userSources", userSources);
		
		for(UserSource userSource : userSources) {
			Integer index = userSource.getTransIndex();
			if(index != null) {
				stat.get(userSource.getSite().getName()).get(index).addAmount();
				if(userSource.getVisited() != null && userSource.getVisited() == true) {
					stat.get(userSource.getSite().getName()).get(index).addArrive();
				}
				if(userSource.getOrdered() != null && userSource.getOrdered() == true) {
					stat.get(userSource.getSite().getName()).get(index).addOrder();
				}
			}
		}
		
		modelAndView.addObject("stat", stat);
		modelAndView.addObject("selectDate", selectDate);
		
		return modelAndView;
	}
	
	/**
	 * 
	 * @param request
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/export", method = RequestMethod.GET)
	@MenuSetting("submenu-source-stat-management")
	public ModelAndView export(@Secure Login login, 
			@RequestParam(value = "site", required = false) Long siteId,
			@RequestParam(value = "selectDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date selectDate,
			HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("user-source-export.xls"));
		
		if(selectDate == null) {
			selectDate = new Date();
		}
		
		Date monthFirst = DateUtils.getFirstMonthDay(selectDate);
		Date monthLast = DateUtils.getLastMonthDay(selectDate);
		
		List<Site> sites = new ArrayList<Site>();
		
		if(siteId != null) {
			Site site = siteService.load(siteId);
			sites.add(site);
		} else if(login.isAdmin() || login.isRoot()) {
			sites = siteService.list();
		} else if (login.isAreaManager() || login.isAreaServer()) {
			Principal principal = principalService.load(Principal.class, login.getId());
            sites = siteService.listSite(principal);
		} else {
			Site site = login.getSite();
			sites.add(site);
		}
		
		List<UserSource> userSources = new ArrayList<UserSource>();
		userSources = userSourceService.listSource(monthFirst, monthLast, sites);
		Map<String, List<UserSourceTranser>> stat = new HashMap<String, List<UserSourceTranser>>(sites.size());
		
		for(Site site : sites) {
			List<UserSourceTranser> transers = new LinkedList<UserSourceTranser>();
			transers.add(new UserSourceTranser(site, "大众点评"));
			transers.add(new UserSourceTranser(site, "访客"));
			transers.add(new UserSourceTranser(site, "转介绍"));
			transers.add(new UserSourceTranser(site, "店长资源"));
			transers.add(new UserSourceTranser(site, "线下运营"));
			transers.add(new UserSourceTranser(site, "在营续课"));
			transers.add(new UserSourceTranser(site, "结营续课"));
			
			stat.put(site.getName(), transers);
		}
		modelAndView.addObject("userSources", userSources);
		
		
		
		for(UserSource userSource : userSources) {
			Integer index = userSource.getTransIndex();
			if(index != null) {
				stat.get(userSource.getSite().getName()).get(index).addAmount();
				if(userSource.getVisited() != null && userSource.getVisited() == true) {
					stat.get(userSource.getSite().getName()).get(index).addArrive();
				}
				if(userSource.getOrdered() != null && userSource.getOrdered() == true) {
					stat.get(userSource.getSite().getName()).get(index).addOrder();
				}
			}
		}
		
		modelAndView.addObject("stat", stat);
		modelAndView.addObject("selectDate", selectDate);
		
		DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        modelAndView.addObject("fmt", fmt);
        
        NumberFormat numFmt = new DecimalFormat("0");
        modelAndView.addObject("numFmt", numFmt);
		
		return modelAndView;
	}

}
